<template>
  <div class="attachments">
    <el-upload
       action="#"
       ref = "uploadRef"
       :list-type="styleType?`picture-card`:`picture`"
       :file-list="pd.fileList"
       :auto-upload="false"
       :class="{ hide: props.limit ? pd.fileList.length >= props.limit : false }"
       :disabled="props.showList"
       :on-change="handleUpload"
    >
      <el-button type="primary" plain icon="Upload"  v-if="!styleType">上传图片</el-button>
      <el-icon v-else @click="handleCropperPicture" style="width: 100%; height: 100%;">
        <Plus />
      </el-icon>
      <template #file="{ file }">
        <div>
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="预览" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon><ZoomIn /></el-icon>
            </span>
            <span class="el-upload-list__item-delete" @click="handleDelete(file)">
              <el-icon><Delete /></el-icon>
            </span>
          </span>
        </div>
        <div class="rightCheck" v-show="file.check">
          <el-icon>
            <Check />
          </el-icon>
        </div>
      </template>
      <!-- 上传提示 -->
      <template v-if="showTip" #tip>
        <div>
          请上传
          <template v-if="fileSize">
            大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
          </template>
          <template v-if="type">
            格式为 <b style="color: #f56c6c">{{ type.join("/") }}</b>
          </template>
          的文件
          <template v-if="limit">
            还剩余 <b style="color: #f56c6c">{{ residueNum }}个</b> 可选择
          </template>
        </div>
      </template>
    </el-upload>

    <!--切图弹窗-->
    <imgCut
      :cutout-show="pd.cutoutShow"
      :img-file="pd.fileBack"
      :id-list="props.idList[0]"
      @ok="handleCropperClose"
    />

    <!--列表弹窗-->
    <pictureList
      :limit="props.limit"
      :show-list="pd.imgListShow"
      :img-file="pd.fileList"
      :id-list="props.idList[0]"
      @ok="listReturn"
    />

    <!--大图预览-->
    <el-dialog v-model="pd.imgShow" width="500px">
      <el-image :src="pd.dialogImageUrl" fit="fill" />
    </el-dialog>

  </div>
</template>

<script setup lang="ts" name="pictureUpload">
import {Check, Delete, Plus, ZoomIn} from '@element-plus/icons-vue'
import "vue-cropper/dist/index.css";
import { getCurrentInstance, reactive } from "vue";
import {delOss, listByIds, listOss, OssQuery} from "@/views/system/minio/api";
import {listProductOss} from "@/views/wms/product/api";
import imgCut from "@/views/system/minio/picture.vue";
import pictureList from "@/views/system/minio/pictureList.vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(["ok"]);

const props = defineProps({
  idList: {
    type: <any>[],
    default: [],
  },
  // 是否为菜单图片
  isMenu: {
    type: Boolean,
    default: false,
  },
  // 数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 样式
  styleType: {
    type: Boolean,
    default: true,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  type: {
    type: Array,
    default: () => ["png", "jpg", "jpeg"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  // 是否弹出列表
  showList: {
    type: Boolean,
    default: false
  },
})

const showTip = computed(
  () => props.isShowTip && (props.type || props.fileSize)
);

const residueNum = computed(
  () => props.limit - pd.fileList.length
);

const pd = reactive({
  imgListShow: false,// 图片列表弹窗
  imgShow: false,// 图片预览弹窗
  dialogImageUrl: '',//图片预览对象
  cutoutShow: false,// 切图弹窗
  fileList: [] as any,//勾选图片数组
  fileBack: null as any,//选中的图片数据
  uploadLimit: 5,
  total: 0,
})

watch(() => props.idList, (val,oldValue) => {
  // console.log("val: ",val,"oldValue: ",oldValue)
  if (val.length > 0 && val[0] != null) {
    if(props.isMenu){
      getMenu(val[0])
    }else{
      getInfo(val[0])
    }
  }else{
    pd.fileList = []
  }
}, { deep: true, immediate: true });

//获取相应产品图片
async function getInfo(id: string | number) {
  const res = await listProductOss(id)
  res ? pd.fileList = res : pd.fileList = []
  emit("ok",pd.fileList)
}

//获取相应菜单图片
async function getMenu(id: string | number) {
  pd.fileList = [];
  const res = await listByIds(id)
  res.data ? pd.fileList = res.data: pd.fileList = []
  emit("ok",pd.fileList)
}

//打开列表还是切图弹窗
function handleCropperPicture() {
  if (props.showList) {
    pd.imgListShow = true
  }
}

//图片列表返回
function listReturn(value: any){
  pd.imgListShow = false
  if (value[0] != false){
    pd.fileList = value
    emit("ok",value)
  }
}

// 是否查看大图
function handlePictureCardPreview(uploadFile: any){
  pd.dialogImageUrl = uploadFile.url
  pd.imgShow = true
}

// 文件删除
async function handleDelete(uploadFile: any) {
  if (props.isMenu){
    pd.fileList = [];
    emit('ok', null)
  }else{
    let ossIdFile = pd.fileList.filter((item:any) => {
      return item.url != uploadFile.url
    })
    pd.fileList = ossIdFile;
    emit('ok', ossIdFile)
  }
}

//添加文件
async function handleUpload(uploadFile: UploadFile) {
  if (!props.showList) pd.fileList = []
  pd.fileBack = uploadFile.raw;
  let size = uploadFile.raw.size / 1024 / 1024
  if (uploadFile.raw.type.indexOf("image/") == -1) {
    proxy?.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
    return false;
  } else if (props.fileSize && size > props.fileSize) {
    proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
    return false;
  }
  pd.cutoutShow = true
}

// 关闭切图窗口
function handleCropperClose(value: any) {
  // console.log("子组件传进来的value",value)
  pd.cutoutShow = false;
  emit('ok', value)
}
</script>

<style lang="scss" scoped>

.rightCheck {
  right: -15px;
  top: -6px;
  width: 40px;
  height: 24px;
  background: var(--el-color-success);
  text-align: center;
  transform: rotate(45deg);
  position: absolute;

  i {
    color: #fff;
    font-size: 12px;
    margin-top: 11px;
    transform: rotate(-45deg);
  }
}
</style>
<!-- 覆盖elementUI样式 -->
<style lang="scss">
.hide .el-upload--picture-card {
  display: none;
}

.head-container {
  text-align: center;
}

.listImg {
  .el-upload-list__item {
    width: 100px !important;
    height: 124px !important;

    .text {
      width: 100px;
      line-height: 20px;
      height: 20px;
      display: block;
      overflow: hidden;
      background: #f6f6f6;
      padding: 0 5px;
      text-align: center;
      position: absolute;
      bottom: -2px;
    }
  }

  .el-upload--picture-card {
    width: 100px !important;
    height: 124px !important;
  }
}

.uploadImg {
  .el-upload-list__item {
    width: 90px !important;
    height: 90px !important;
  }

  .el-upload--picture-card {
    width: 90px !important;
    height: 90px !important;
  }
}
</style>
